/**
 * 
 */
package co.fitstart.coach.web.controller;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.support.HttpResult;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.coach.handler.DistanceHandler;
import co.fitstart.coach.service.CourseService;
import co.fitstart.coach.service.PrincipalService;
import co.fitstart.coach.service.SigninService;
import co.fitstart.coach.web.resolver.Secure;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.site.Site;
import co.fitstart.entity.user.bwh.BwhRecord;

/**
 * @author downpour
 *
 */
@Controller
@RequestMapping("")
public class SigninController {
    
    private static final Logger logger = LoggerFactory.getLogger(SigninController.class);
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private SigninService signinService;
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private DistanceHandler distanceHandler;
    
    /**
     * Sign in
     * 
     * @param request 
     * @return
     */
    @RequestMapping(value = "/signin", method = RequestMethod.GET)
    @WechatJsConfig
    public ModelAndView signin(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView("sign/signin-index");
        
        return modelAndView;
    }
    
    /**
     * 
     * @param courseScheduleId
     * @param timestamp
     * @param longitude
     * @param latitude
     * @return
     */
    @RequestMapping(value = "/signin/valid", method = RequestMethod.POST, params = "course")
    public @ResponseBody String validLocation(@Secure(property = "id") Long coachId,
                                              @RequestParam("course") Long courseScheduleId,
                                              @RequestParam("timestamp") Long timestamp,
                                              @RequestParam(name = "longitude", required = false) Double longitude,
                                              @RequestParam(name = "latitude", required = false) Double latitude,
                                              @RequestParam(value = "ignoretime", required =false) boolean debug) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            logger.info("#validLocation with params longitude[{}] latitude[{}]", longitude, latitude);
            
            Principal coach = principalService.load(Principal.class, coachId);
            
            CourseSchedule courseSchedule = courseService.loadCourseSchedule(courseScheduleId);
            Site site = courseSchedule.getSite();
            
            if(coach != courseSchedule.getCoach()) {
                httpResult.fail().message("你不是当前课程上课教练，不能签到");
                return JsonUtils.toJsonString(httpResult);
            }
            
            if(longitude != null && latitude != null) {
                int distance = distanceHandler.getDistance(longitude, latitude, site.getLongitude(), site.getLatitude());
                if(distance > 1000) {
                    if(debug != true) {
                      httpResult.fail().message("请在门店1000米范围内进行扫码签到");
                      return JsonUtils.toJsonString(httpResult);
                    }
                }
            }
            
            Long currentTime = new Date().getTime();
            if(currentTime - timestamp > 60000) {
                if(debug != true) {
                    httpResult.fail().message("当前二维码已失效，请重新刷新");
                    return JsonUtils.toJsonString(httpResult);
                }
            }
            
            if(!courseSchedule.couldSignin()) {
                httpResult.fail().message("当前课程不在签到时间 ~");
                return JsonUtils.toJsonString(httpResult);
            }
            
            httpResult.success()
                      .message("符合签到条件，正在跳转");
            
            
        } catch (Exception e) {
            
            logger.error("#validLocation occurs error: ", e);
            httpResult.fail().message("校验签到码错误");
        }
        
        return JsonUtils.toJsonString(httpResult);
    }
    
    /**
     * Sign in
     * 
     * @param courseScheduleId
     * @return
     */
    @RequestMapping(value = "/scan-result", method = RequestMethod.POST, params = "course")
    public ModelAndView scan(@RequestParam("course") Long courseScheduleId) {
        
        ModelAndView modelAndView = new ModelAndView("sign/signin-course");
        
        CourseSchedule courseSchedule = courseService.loadCourseSchedule(courseScheduleId);
        
        if(!courseSchedule.couldSignin()) {
            modelAndView.setViewName("sign/signin-time-error");
            modelAndView.addObject("message", "当前课程不在签到时间 ~");
            return modelAndView;
        }
        
        int finished = courseService.countFinishedSchedule(courseSchedule.getCourseRound());
        boolean couldEdit = courseSchedule.getCourseRound().isFullInTarget() && (finished == 0 || finished % 4 == 3) && !courseSchedule.getCourse().isExperience();
        modelAndView.addObject("couldEdit", couldEdit);
        
        modelAndView.addObject("courseSchedule", courseSchedule);
        
        return modelAndView;
    }

    /**
     * 
     * @param coachId
     * @param courseScheduleId
     * @param admin
     * @param comment
     * @return
     */
    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    public @ResponseBody String onSignin(@Secure(property = "id") Long coachId,
                                         @RequestParam("course") Long courseScheduleId,
                                         @RequestParam(value = "admin", required = false, defaultValue = "false") boolean admin,
                                         @RequestParam(value = "comment", required = false) String comment,
                                         BwhRecord bwhRecord){
        
        Result result = new Result();
        
        try {
            
            logger.info("#onSignin with params coachId [{}], courseScheduleId [{}], admin [{}] comment[{}]", coachId, courseScheduleId, admin, comment);
            
            Principal coach = principalService.load(Principal.class, coachId);
            
            CourseSchedule courseSchedule = courseService.loadCourseSchedule(courseScheduleId);
            
            if(coach != courseSchedule.getCoach()) {
                result.fail().message("你不是当前课程上课教练，不能签到");
            } else {
             // do signin here
                int finished = courseService.countFinishedSchedule(courseSchedule.getCourseRound());
                signinService.signin(coach, courseSchedule, bwhRecord, comment, admin, finished);
                
//                tencentHandler.sendMessage("您有新的工资到账，请去系统查看", coach.getMobile());
                
                result.success()
                      .message("签到成功");
            }
        } catch(BusinessException e){
            
            logger.error("#onSignin - ", e);
            
            result.fail().message(e.getMessage());
            
        } catch(Exception e) {
            
            logger.error("#onSignin - ", e);
            
            result.fail().message("签到失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param coachId
     * @return
     */
    @RequestMapping(value = "/signin-success", method = RequestMethod.GET)
    public ModelAndView success(@Secure(property = "id") Long coachId){
        ModelAndView modelAndView = new ModelAndView("sign/signin-success");
        
        Principal coach = principalService.load(Principal.class, coachId);
        
        double hour = signinService.getCoachHour(coach);
        modelAndView.addObject("hour", hour);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param message
     * @return
     */
    @RequestMapping(value = "/signin-error", method = RequestMethod.GET)
    public String error(@RequestParam("message") String message){
        return "sign/signin-error";
    }
    
}
